package com.logic.landseaserver.models.workorder.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.logic.common.security.SecurityUtils;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.common.LandeaConstants.OrderType;
import com.logic.landseaserver.common.LandeaConstants.RoleCode;
import com.logic.landseaserver.common.LandeaConstants.SatisfactionLevel;
import com.logic.landseaserver.common.LandeaConstants.ScheduleStatus;
import com.logic.landseaserver.common.LandeaConstants.ServiceType;
import com.logic.landseaserver.common.LandeaConstants.SourceChannel;
import com.logic.landseaserver.common.LandeaConstants.WorkOrderStatus;
import com.logic.landseaserver.common.config.FileConfiguration;
import com.logic.landseaserver.common.config.SendMsgConfiguration;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.common.exception.ResultCodes.UserAnswersResultCode;
import com.logic.landseaserver.common.exception.ResultCodes.WorkOrderResultCode;
import com.logic.landseaserver.common.util.DateUtil;
import com.logic.landseaserver.common.util.SMSUtil;
import com.logic.landseaserver.domain.Project;
import com.logic.landseaserver.domain.WorkOrder;
import com.logic.landseaserver.domain.WorkOrderAppraise;
import com.logic.landseaserver.domain.WorkOrderSchedule;
import com.logic.landseaserver.models.workorder.bean.AssignedUserResp;
import com.logic.landseaserver.models.workorder.bean.CheckUserRoleResp;
import com.logic.landseaserver.models.workorder.bean.EffectiveProjectResp;
import com.logic.landseaserver.models.workorder.bean.OrderTypeCodeResp;
import com.logic.landseaserver.models.workorder.bean.ProjectAndRoomResp;
import com.logic.landseaserver.models.workorder.bean.WorkOrderDetailResp;
import com.logic.landseaserver.models.workorder.bean.WorkOrderListResp;
import com.logic.landseaserver.models.workorder.bean.WorkOrderReportListResp;
import com.logic.landseaserver.models.workorder.bean.WorkOrderReq;
import com.logic.landseaserver.persistence.read.BalanceSheetRecordReadMapper;
import com.logic.landseaserver.persistence.read.CustomerReadMapper;
import com.logic.landseaserver.persistence.read.ExpensesReadMapper;
import com.logic.landseaserver.persistence.read.ProjectReadMapper;
import com.logic.landseaserver.persistence.read.RoomReadMapper;
import com.logic.landseaserver.persistence.read.WorkOrderAppraiseReadMapper;
import com.logic.landseaserver.persistence.read.WorkOrderReadMapper;
import com.logic.landseaserver.persistence.read.WorkOrderScheduleReadMapper;
import com.logic.landseaserver.persistence.write.WorkOrderAppraiseWriteMapper;
import com.logic.landseaserver.persistence.write.WorkOrderScheduleWriteMapper;
import com.logic.landseaserver.persistence.write.WorkOrderWriteMapper;
import com.logic.landseaserver.service.ICustomer;
import com.logic.landseaserver.ws.dto.CustomerDTO;
import com.logic.landseaserver.ws.response.AuthorizedItemResp;
import com.logic.landseaserver.ws.response.ExpenseTypeResp;
import com.logic.landseaserver.ws.response.RoomResp;
import com.logic.landseaserver.ws.response.TenantDetailResp;
import com.logic.system.domain.Configuration;
import com.logic.system.persistence.read.UserReadMapper;
import com.logic.system.service.impl.ConfigurationService;
import com.logic.system.ws.dto.UserRoleDTO;

@Service
public class WorkOrderService implements EnvironmentAware
{
    private static final String ENV_FILE_PATH = "logic.file.path.";
    
    private static final String EXCEL_PATH = "excelPath";
    
    private static final String REMOTE_PATH = "remote";
    
    private static RelaxedPropertyResolver propertyResolver;
    
    private static final Logger LOGGER = LoggerFactory.getLogger(WorkOrderService.class);
    
    @Autowired
    private ICustomer iCustomer;
    
    @Autowired
    private CustomerReadMapper customerReadMapper;
    
    @Autowired
    private RoomReadMapper roomReadMapper;
    
    @Autowired
    private ProjectReadMapper projectReadMapper;
    
    @Autowired
    private WorkOrderReadMapper workOrderReadMapper;
    
    @Autowired
    private WorkOrderWriteMapper workOrderWriteMapper;
    
    @Autowired
    private WorkOrderScheduleWriteMapper workOrderScheduleWriteMapper;
    
    @Autowired
    private WorkOrderScheduleReadMapper workOrderScheduleReadMapper;
    
    @Autowired
    private WorkOrderAppraiseWriteMapper workOrderAppraiseWriteMapper;
    
    @Autowired
    private WorkOrderAppraiseReadMapper workOrderAppraiseReadMapper;
    
    @Autowired
    private ConfigurationService configurationService;
    
    @Autowired
    private SendMsgConfiguration sendMsgConfiguration;
    
    @Autowired
    private UserReadMapper userReadMapper;
    
    @Autowired
    private ExpensesReadMapper expensesReadMapper;
    
    @Autowired
    private FileConfiguration fileConfiguration;
    
    @Autowired
    private BalanceSheetRecordReadMapper balanceSheetRecordReadMapper;
    
    public EffectiveProjectResp effectiveProjectForWeChat()throws LandseaException
    {
        EffectiveProjectResp resultResp = new EffectiveProjectResp();
        try{
            Integer userId = SecurityUtils.getCurrentLogin().getUserId();
            CustomerDTO customerDTO = iCustomer.getCustomerInfo(userId);
            if (null == customerDTO)
            {
                throw LandseaException.createException(WorkOrderResultCode.E00850001);
            }
            else
            {
                resultResp.setUserId(userId);
                resultResp.setUserName(customerDTO.getName());
                resultResp.setUserPhone(customerDTO.getPhone());
                List<ProjectAndRoomResp> projectAndRoomResps = projectReadMapper.getEffectiveProject(userId);
                //没有项目
                if (CollectionUtils.isEmpty(projectAndRoomResps))
                {
                    projectAndRoomResps = projectReadMapper.getAllEffectiveProject();
                    for (ProjectAndRoomResp projectAndRoomResp : projectAndRoomResps)
                    {
                        List<ExpenseTypeResp> serviceType1 = expensesReadMapper.selectFee(OrderType.AREAREPAIR);
                        List<ExpenseTypeResp> serviceType2 = expensesReadMapper.selectFee(OrderType.SERVICEWO);
                        for (ExpenseTypeResp expenseTypeResp : serviceType2)
                        {
                            if (ServiceType._WOST5.equals(expenseTypeResp.getTypeCode()))
                            {
                                continue;
                            }
                            else
                            {
                                serviceType1.add(expenseTypeResp);
                            }             
                        }
                        projectAndRoomResp.setServiceTypeResps(serviceType1);
                    }
                    resultResp.setProjectResps(projectAndRoomResps);
                }
                //有项目
                else
                {
                    for (ProjectAndRoomResp projectAndRoomResp : projectAndRoomResps)
                    {
                        List<RoomResp> roomResps = roomReadMapper.getEffectiveRoom(userId,projectAndRoomResp.getPrjId());
                        //没有房间
                        if (CollectionUtils.isEmpty(roomResps))
                        {
                            projectAndRoomResp.setRoomResps(null); 
                            List<ExpenseTypeResp> serviceType1 = expensesReadMapper.selectFee(OrderType.AREAREPAIR);
                            List<ExpenseTypeResp> serviceType2 = expensesReadMapper.selectFee(OrderType.SERVICEWO);
                            for (ExpenseTypeResp expenseTypeResp : serviceType2)
                            {
                                if (ServiceType._WOST5.equals(expenseTypeResp.getTypeCode()))
                                {
                                    continue;
                                }
                                else
                                {
                                    serviceType1.add(expenseTypeResp);
                                }             
                            }
                            projectAndRoomResp.setServiceTypeResps(serviceType1);
                            
                        }
                        else
                        {
                            projectAndRoomResp.setRoomResps(roomResps); 
                            List<ExpenseTypeResp> serviceType1 = expensesReadMapper.selectFee(OrderType.COMPLETEWO);
                            List<ExpenseTypeResp> serviceType2 = expensesReadMapper.selectFee(OrderType.SERVICEWO);
                            List<ExpenseTypeResp> serviceType3 = expensesReadMapper.selectFee(OrderType.AREAREPAIR);
                            for (ExpenseTypeResp expenseTypeResp : serviceType2)
                            {
                                if (ServiceType._WOST5.equals(expenseTypeResp.getTypeCode()))
                                {
                                    continue;
                                }
                                else
                                {
                                    serviceType3.add(expenseTypeResp);
                                }             
                            }
                            for (ExpenseTypeResp expenseTypeResp : serviceType1)
                            {
                                if (ServiceType._WOAR8.equals(expenseTypeResp.getTypeCode()))
                                {
                                    continue;
                                }
                                else
                                {
                                    serviceType3.add(expenseTypeResp);
                                }
                            }
                            projectAndRoomResp.setServiceTypeResps(serviceType3);
                        } 
                    }
                    resultResp.setProjectResps(projectAndRoomResps);
                }    
            }
        }
        catch (LandseaException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            LOGGER.error("effectiveProjectForWeChat|查询租客信息失败.", e);
            throw LandseaException.createException(UserAnswersResultCode.E00750002);
        }
        return resultResp;
    }
    
    public EffectiveProjectResp effectiveProjectForAdmin(String phone)throws LandseaException
    {
        EffectiveProjectResp resultResp = new EffectiveProjectResp();
        try{
            TenantDetailResp resp = customerReadMapper.queryTenantDetailByPhone(phone);
            if (null == resp)
            {
                throw LandseaException.createException(WorkOrderResultCode.E00850001);
            }
            else
            {
                resultResp.setUserId(resp.getUserId());
                resultResp.setUserName(resp.getName());
                resultResp.setUserPhone(phone);
                List<ProjectAndRoomResp> projectAndRoomResps = projectReadMapper.getEffectiveProjectForAdmin(phone);
                //没有项目房间的
                if (CollectionUtils.isEmpty(projectAndRoomResps))
                {
                    List<AuthorizedItemResp> authorizedProjectResps = projectReadMapper.selectProjectAndCity(SecurityUtils.getCurrentLogin().getUserId());
                    if (CollectionUtils.isEmpty(authorizedProjectResps))
                    {
                        throw LandseaException.createException(WorkOrderResultCode.E00850002); 
                    }
                    else
                    {
                        for (AuthorizedItemResp authorizedItemResp : authorizedProjectResps)
                        {
                            ProjectAndRoomResp parResp = new ProjectAndRoomResp();
                            parResp.setPrjId(authorizedItemResp.getPrjId());
                            parResp.setPrjName(authorizedItemResp.getPrjName()); 
                            
                            List<OrderTypeCodeResp> orderTypeListResps = new ArrayList<OrderTypeCodeResp>();
                            OrderTypeCodeResp codeResp1 = new  OrderTypeCodeResp();
                            codeResp1.setCode(OrderType.AREAREPAIR);
                            codeResp1.setName(balanceSheetRecordReadMapper.selectExpenditure(OrderType.AREAREPAIR));
                            List<ExpenseTypeResp> serviceType1 = expensesReadMapper.selectFee(OrderType.AREAREPAIR);
                            codeResp1.setServiceTypeResps(serviceType1);
                            orderTypeListResps.add(codeResp1);
                            
                            OrderTypeCodeResp codeResp2 = new  OrderTypeCodeResp();
                            codeResp2.setCode(OrderType.SERVICEWO);
                            codeResp2.setName(balanceSheetRecordReadMapper.selectExpenditure(OrderType.SERVICEWO));
                            List<ExpenseTypeResp> serviceType2 = expensesReadMapper.selectFee(OrderType.SERVICEWO);
                            codeResp2.setServiceTypeResps(serviceType2);
                            orderTypeListResps.add(codeResp2);
                            
                            OrderTypeCodeResp codeResp3 = new  OrderTypeCodeResp();
                            codeResp3.setCode(OrderType.OTHERWO);
                            codeResp3.setName(balanceSheetRecordReadMapper.selectExpenditure(OrderType.OTHERWO));
                            List<ExpenseTypeResp> serviceType3 = expensesReadMapper.selectFee(OrderType.OTHERWO);
                            codeResp3.setServiceTypeResps(serviceType3);
                            orderTypeListResps.add(codeResp3);
                            
                            parResp.setOrderTypeListResps(orderTypeListResps);
                            
                            projectAndRoomResps.add(parResp);
                        }
                        
                        resultResp.setProjectResps(projectAndRoomResps);
                    } 
                }
                //有项目房间的
                else
                {
                    for (ProjectAndRoomResp projectAndRoomResp : projectAndRoomResps)
                    {
                        List<RoomResp> roomResps = roomReadMapper.getEffectiveRoomForAdmin(phone,projectAndRoomResp.getPrjId());
                       //没有房间 的
                        if (CollectionUtils.isEmpty(roomResps))
                        {
                            projectAndRoomResp.setRoomResps(null); 
                            
                            List<OrderTypeCodeResp> orderTypeListResps = new ArrayList<OrderTypeCodeResp>();
                            
                            OrderTypeCodeResp codeResp2 = new  OrderTypeCodeResp();
                            codeResp2.setCode(OrderType.SERVICEWO);
                            codeResp2.setName(balanceSheetRecordReadMapper.selectExpenditure(OrderType.SERVICEWO));
                            List<ExpenseTypeResp> serviceType2 = expensesReadMapper.selectFee(OrderType.SERVICEWO);
                            codeResp2.setServiceTypeResps(serviceType2);
                            orderTypeListResps.add(codeResp2);
                            
                            OrderTypeCodeResp codeResp3 = new  OrderTypeCodeResp();
                            codeResp3.setCode(OrderType.OTHERWO);
                            codeResp3.setName(balanceSheetRecordReadMapper.selectExpenditure(OrderType.OTHERWO));
                            List<ExpenseTypeResp> serviceType3 = expensesReadMapper.selectFee(OrderType.OTHERWO);
                            codeResp3.setServiceTypeResps(serviceType3);
                            orderTypeListResps.add(codeResp3);
                            
                            OrderTypeCodeResp codeResp4 = new  OrderTypeCodeResp();
                            codeResp4.setCode(OrderType.AREAREPAIR);
                            codeResp4.setName(balanceSheetRecordReadMapper.selectExpenditure(OrderType.AREAREPAIR));
                            List<ExpenseTypeResp> serviceType4 = expensesReadMapper.selectFee(OrderType.AREAREPAIR);
                            codeResp4.setServiceTypeResps(serviceType4);
                            orderTypeListResps.add(codeResp4);
                            projectAndRoomResp.setOrderTypeListResps(orderTypeListResps);
                        }
                        else
                        {
                            projectAndRoomResp.setRoomResps(roomResps);
                            
                            projectAndRoomResp.setOrderTypeResps(null);
                            projectAndRoomResp.setServiceTypeResps(null);
                            
                            List<OrderTypeCodeResp> orderTypeListResps = new ArrayList<OrderTypeCodeResp>();
                            OrderTypeCodeResp codeResp1 = new  OrderTypeCodeResp();
                            codeResp1.setCode(OrderType.COMPLETEWO);
                            codeResp1.setName(balanceSheetRecordReadMapper.selectExpenditure(OrderType.COMPLETEWO));
                            List<ExpenseTypeResp> serviceType1 = expensesReadMapper.selectFee(OrderType.COMPLETEWO);
                            codeResp1.setServiceTypeResps(serviceType1);
                            orderTypeListResps.add(codeResp1);
                            
                            OrderTypeCodeResp codeResp2 = new  OrderTypeCodeResp();
                            codeResp2.setCode(OrderType.SERVICEWO);
                            codeResp2.setName(balanceSheetRecordReadMapper.selectExpenditure(OrderType.SERVICEWO));
                            List<ExpenseTypeResp> serviceType2 = expensesReadMapper.selectFee(OrderType.SERVICEWO);
                            codeResp2.setServiceTypeResps(serviceType2);
                            orderTypeListResps.add(codeResp2);
                            
                            OrderTypeCodeResp codeResp3 = new  OrderTypeCodeResp();
                            codeResp3.setCode(OrderType.AREAREPAIR);
                            codeResp3.setName(balanceSheetRecordReadMapper.selectExpenditure(OrderType.AREAREPAIR));
                            List<ExpenseTypeResp> serviceType3 = expensesReadMapper.selectFee(OrderType.AREAREPAIR);
                            codeResp3.setServiceTypeResps(serviceType3);
                            orderTypeListResps.add(codeResp3);
                            
                            OrderTypeCodeResp codeResp4 = new  OrderTypeCodeResp();
                            codeResp4.setCode(OrderType.OTHERWO);
                            codeResp4.setName(balanceSheetRecordReadMapper.selectExpenditure(OrderType.OTHERWO));
                            List<ExpenseTypeResp> serviceType4 = expensesReadMapper.selectFee(OrderType.OTHERWO);
                            codeResp4.setServiceTypeResps(serviceType4);
                            orderTypeListResps.add(codeResp4);
                            projectAndRoomResp.setOrderTypeListResps(orderTypeListResps);
                            
                        } 
                    }
                    resultResp.setProjectResps(projectAndRoomResps);
                }    
            }
        }
        catch (LandseaException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            LOGGER.error("effectiveProjectForAdmin|查询租客信息失败.", e);
            throw LandseaException.createException(UserAnswersResultCode.E00750002);
        }
        return resultResp;
    }
    
    private String generateWONo(String prjCode, Integer maxWOCode)
    {
        String WOSn = prjCode + new DecimalFormat("000000").format(maxWOCode);
        return WOSn;
    }
    
    public void insertWorkOrder(WorkOrderReq workOrderReq) throws LandseaException
    {
        try
        {
            WorkOrder addWorkOrder = new WorkOrder();
            addWorkOrder.initCommonField();
            Integer maxWOCode = workOrderReadMapper.getMaxWOCode();
            //新建工单
            if (null == workOrderReq.getPreviousId() || "".equals(workOrderReq.getPreviousId()))
            {  
                //创建工单 工单进度
                addWorkOrder.setScheduleStatus(ScheduleStatus.CREATE);
                addWorkOrder.setRestart(false);
                addWorkOrder.setOrderCreatedTime(addWorkOrder.getCreatedDtm());
                if (null == workOrderReq.getProjectId() || "".equals(workOrderReq.getProjectId()))
                {
                    throw LandseaException.createException(WorkOrderResultCode.E00850004); 
                }
                Project project = projectReadMapper.selectByPrimaryKey(workOrderReq.getProjectId());
                String workOrderCode = generateWONo("WO"+project.getPrjCode(), maxWOCode);
                addWorkOrder.setDemand(workOrderReq.getDemand());
                addWorkOrder.setOrderCreatedTime(addWorkOrder.getOrderCreatedTime());
                //工单状态
                addWorkOrder.setWorkOrderStatus(WorkOrderStatus.TOBESENT);
                addWorkOrder.setPictureId(workOrderReq.getPictureId());
                addWorkOrder.setProjectId(workOrderReq.getProjectId());
                addWorkOrder.setSourceChannel(workOrderReq.getSourceChannel());
                addWorkOrder.setUserId(workOrderReq.getUserId());
                addWorkOrder.setUserName(workOrderReq.getUserName());
                addWorkOrder.setUserPhone(workOrderReq.getUserPhone());
                addWorkOrder.setWorkOrderCode(workOrderCode);
                //如果租客未入住任何房间，则只能新增咨询工单
                
                addWorkOrder.setRoomId(workOrderReq.getRoomId());
                addWorkOrder.setServiceType(workOrderReq.getServiceType());
                //工单类型
                if (null == workOrderReq.getOrderType() || "".equals(workOrderReq.getOrderType()))
                {
                    
                    addWorkOrder.setOrderType(OrderType.SERVICEWO);
                    
                }
                else
                {
                    addWorkOrder.setOrderType(workOrderReq.getOrderType());
                }
                workOrderWriteMapper.insertSelective(addWorkOrder);
            }
            //重启工单
            else
            {
                WorkOrder previousWorkOrder = workOrderReadMapper.selectByPrimaryKey(workOrderReq.getPreviousId());
                if (null == previousWorkOrder)
                {
                    throw LandseaException.createException(WorkOrderResultCode.E00850005); 
                }
                if (null != previousWorkOrder.getPreviousId() || 
                    WorkOrderStatus.FORCEDFINISH == previousWorkOrder.getWorkOrderStatus())
                {
                    throw LandseaException.createException(WorkOrderResultCode.E00850006); 
                }
                //重启的旧工单修改重启状态
                workOrderWriteMapper.updateRestartByPrimaryKey(workOrderReq.getPreviousId());
                WorkOrder restartWorkOrder = new WorkOrder();
                //重启工单的信息
                restartWorkOrder.initCommonField();
                restartWorkOrder.setDemand(workOrderReq.getDemand());
                restartWorkOrder.setOrderCreatedTime(restartWorkOrder.getCreatedDtm());
                restartWorkOrder.setSourceChannel(SourceChannel.WECHAT);
                restartWorkOrder.setRestart(false);
                restartWorkOrder.setPreviousId(workOrderReq.getPreviousId());
                //工单状态
                restartWorkOrder.setWorkOrderStatus(WorkOrderStatus.TOBESENT);
                //进度状态
                restartWorkOrder.setScheduleStatus(ScheduleStatus.RESTART);
                //工单类型
                restartWorkOrder.setOrderType(previousWorkOrder.getOrderType());
                restartWorkOrder.setPictureId(previousWorkOrder.getPictureId());
                restartWorkOrder.setProjectId(previousWorkOrder.getProjectId());
                restartWorkOrder.setRoomId(previousWorkOrder.getRoomId());
                restartWorkOrder.setServiceType(previousWorkOrder.getServiceType());
                restartWorkOrder.setUserId(previousWorkOrder.getUserId());
                restartWorkOrder.setUserName(previousWorkOrder.getUserName());
                restartWorkOrder.setUserPhone(previousWorkOrder.getUserPhone());
                
                Project project = projectReadMapper.selectByPrimaryKey(previousWorkOrder.getProjectId());
                String workOrderCode = generateWONo("WO"+project.getPrjCode(), maxWOCode);
                restartWorkOrder.setWorkOrderCode(workOrderCode);
                
                restartWorkOrder.setOrderCreatedTime(restartWorkOrder.getCreatedDtm());
                workOrderWriteMapper.insertSelective(restartWorkOrder);
            } 
        }
        catch (LandseaException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            LOGGER.error("insertWorkOrder|新增工单失败.", e);
            throw LandseaException.createException(WorkOrderResultCode.E00850007);
        }
        
    }
    
    public void editWorkOrder(WorkOrderReq workOrderReq) throws LandseaException
    {
        try
        {
            WorkOrder workOrder = workOrderReadMapper.selectByPrimaryKey(workOrderReq.getId());
            WorkOrder editWorkOrder = new WorkOrder();
            if(null == workOrder)
            {
                throw LandseaException.createException(WorkOrderResultCode.E00850009);
            }
            //如果没有指派人说明工单只是在编辑基本信息部分
            editWorkOrder.setId(workOrderReq.getId());
            if (null == workOrderReq.getAssignedUserId() )
            {
                //不是待派工不允许编辑
                if (!WorkOrderStatus.TOBESENT.equals(workOrder.getWorkOrderStatus()))
                {
                    throw LandseaException.createException(WorkOrderResultCode.E008500010);
                }
                editWorkOrder.setDemand(workOrderReq.getDemand());
                editWorkOrder.setUserId(workOrderReq.getUserId());
                editWorkOrder.setUserName(workOrderReq.getUserName());
                editWorkOrder.setUserPhone(workOrderReq.getUserPhone());
                editWorkOrder.setProjectId(workOrderReq.getProjectId());
                editWorkOrder.setRoomId(workOrderReq.getRoomId());
                editWorkOrder.setServiceType(workOrderReq.getServiceType());
                editWorkOrder.setPictureId(workOrderReq.getPictureId());
                //编辑一定是有工单类型的
                editWorkOrder.setOrderType(workOrderReq.getOrderType());
                
                editWorkOrder.setWorkOrderStatus(WorkOrderStatus.TOBESENT);
                editWorkOrder.setOrderCreatedTime(workOrder.getOrderCreatedTime());
                editWorkOrder.setScheduleStatus(workOrder.getScheduleStatus());
                editWorkOrder.setSourceChannel(workOrder.getSourceChannel());
                editWorkOrder.setCreatedBy(workOrder.getCreatedBy());
                editWorkOrder.setCreatedDtm(workOrder.getCreatedDtm());
                
            }
            //已经指派人了人
            else
            {
                if (!(WorkOrderStatus.FORCEDFINISH).equals( workOrderReq.getWorkOrderStatus()) &&
                    !(WorkOrderStatus.NORMALFINISH).equals( workOrderReq.getWorkOrderStatus()) )
                {
                    editWorkOrder.setAssignedUserId(workOrderReq.getAssignedUserId());
                    editWorkOrder.setAssignedUserName(workOrderReq.getAssignedUserName());
                    //已派工还未处理
                    if (null == workOrderReq.getWorkOrderSchedule())
                    {
                        editWorkOrder.setWorkOrderStatus(WorkOrderStatus.SENTED);
                    }
                    //处理中
                    else
                    {   
                        WorkOrderSchedule insertWorkOrderSchedule = new WorkOrderSchedule();
                        insertWorkOrderSchedule.initCommonField();
                        insertWorkOrderSchedule.setHandleTime(insertWorkOrderSchedule.getCreatedDtm());
                        insertWorkOrderSchedule.setProcessingProgress(workOrderReq.getWorkOrderSchedule().getProcessingProgress());
                        insertWorkOrderSchedule.setUserId(workOrderReq.getWorkOrderSchedule().getId());
                        insertWorkOrderSchedule.setUserName(workOrderReq.getWorkOrderSchedule().getUserName());
                        insertWorkOrderSchedule.setWorkOrderId(workOrderReq.getId());
                        workOrderScheduleWriteMapper.insertSelective(insertWorkOrderSchedule);
                        editWorkOrder.setNextFollowTime(workOrderReq.getNextFollowTime());
                        
                        editWorkOrder.setWorkOrderStatus(WorkOrderStatus.HANDLING);
                        editWorkOrder.setScheduleStatus(ScheduleStatus.HANDLE);
                        
                    }   
                }
                else
                {
                    editWorkOrder.setEndOfEvent(workOrderReq.getEndOfEvent());
                    editWorkOrder.setResponsibleDepartment(workOrderReq.getResponsibleDepartment());
                    editWorkOrder.setWorkOrderStatus(workOrderReq.getWorkOrderStatus());
                    editWorkOrder.setScheduleStatus(ScheduleStatus.COMPLETE);
                }
            }
            editWorkOrder.editInitCommonField();
            workOrderWriteMapper.updateByPrimaryKeySelective(editWorkOrder);
        }
        catch (LandseaException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            LOGGER.error("edittWorkOrder|编辑工单失败.", e);
            throw LandseaException.createException(WorkOrderResultCode.E00850008);
        }
    }
    
    public WorkOrderDetailResp getWorkOrderDetail(Integer id)throws LandseaException
    {
        try
        {
            WorkOrderDetailResp workOrderDetailResp = workOrderReadMapper.selectWorkOrderDetail(id);
            if (null == workOrderDetailResp)
            {
                throw LandseaException.createException(WorkOrderResultCode.E00850005);
            }
            List<WorkOrderSchedule> workOrderSchedules = workOrderScheduleReadMapper.selectWOScheduleByWOId(id);
            if (CollectionUtils.isEmpty(workOrderSchedules))
            {
                workOrderDetailResp.setWorkOrderSchedules(null);
            }
            //如果处理进度不为空，说明有了处理时间
            else
            {
                workOrderDetailResp.setWorkOrderSchedules(workOrderSchedules);
                WorkOrderSchedule workOrderScheduleTime = workOrderScheduleReadMapper.selectHandleTime(id);
                workOrderDetailResp.setHandleTime(workOrderScheduleTime.getHandleTime());
            }
//            //完成时间
//            if (!(WorkOrderStatus.NORMALFINISH.equals(workOrderDetailResp.getWorkOrderStatusCode())) ||
//                !(WorkOrderStatus.FORCEDFINISH.equals(workOrderDetailResp.getWorkOrderStatusCode())))
//            {
//                workOrderDetailResp.setHandledTime(null);
//            }
            if (null == workOrderDetailResp.getPreviousId())
            {
                workOrderDetailResp.setPreviousWOCode(null); 
                //可以指派的管家
                List<AssignedUserResp> assignedUserResps =  workOrderReadMapper.getHouseKeeperByPrjId(workOrderDetailResp.getProjectId());
                workOrderDetailResp.setAssignedUserResps(assignedUserResps);
            }
            else
            {
                WorkOrder workOrder = workOrderReadMapper.selectByPrimaryKey(workOrderDetailResp.getPreviousId());
                if (null == workOrder)
                {
                    workOrderDetailResp.setPreviousWOCode(null); 
                }
                workOrderDetailResp.setPreviousWOCode(workOrder.getWorkOrderCode()); 
                //可以指派的店长
                List<AssignedUserResp> assignedUserResps =  workOrderReadMapper.getManagerByPrjId(workOrderDetailResp.getProjectId());
                workOrderDetailResp.setAssignedUserResps(assignedUserResps);
            }
            //评价时间
            WorkOrderAppraise workOrderAppraise = getWorkOrderAppraise(id);
            if (null != workOrderAppraise)
            {
                workOrderDetailResp.setAppraiseTime(workOrderAppraise.getLastModifiedDtm());
            }
            
            //检查用户的角色
            CheckUserRoleResp roleResp = new CheckUserRoleResp();
            List<UserRoleDTO> userRoleList = userReadMapper.getUserRolesWithCodeByUserId(SecurityUtils.getCurrentLogin().getUserId());
            roleResp.setIsDZ(0);
            roleResp.setIsGJ(0);
            roleResp.setIsQYJL(0);
            roleResp.setIsZBYYFZR(0);
            if (CollectionUtils.isNotEmpty(userRoleList))
            {
                for (UserRoleDTO userRole : userRoleList)
                {
                    String destRoleCode = userRole.getCode();
                    // 检查总部运营负责人
                    if (RoleCode.ZBYYFZR.equals(destRoleCode))
                    {
                        roleResp.setIsZBYYFZR(1);
                    }
                    // 检查区域经理
                    if (RoleCode.QYYYJL.equals(destRoleCode))
                    {
                        roleResp.setIsQYJL(1);
                    }
                    // 检查店长
                    if (RoleCode.DZ.equals(destRoleCode))
                    {
                        roleResp.setIsDZ(1);
                    }
                    // 检查管家
                    if (RoleCode.GJ.equals(destRoleCode))
                    {
                        roleResp.setIsGJ(1);
                    }   
                }
                workOrderDetailResp.setCheckUserRoleResp(roleResp);
            }
            return workOrderDetailResp;
        }
        catch (LandseaException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            LOGGER.error("getWorkOrderDetail|查询工单详情失败.", e);
            throw LandseaException.createException(WorkOrderResultCode.E008500012);
        }
    }
    
    public void insertWorkOrderAppraise(WorkOrderAppraise workOrderAppraise)throws LandseaException
    {
        try
        {
            Integer woId = workOrderAppraise.getWorkOrderId();
            WorkOrder workOrder = workOrderReadMapper.selectByPrimaryKey(woId);
            if (null == workOrder)
            {
                throw LandseaException.createException(WorkOrderResultCode.E00850005);
            }
            if (ScheduleStatus.COMPLETE.equals(workOrder.getScheduleStatus()))
            {
                workOrderWriteMapper.updateScheduleStatusByPrimaryKey(woId);
                if (workOrderAppraise.getAttitude().intValue()>=2 &&
                    workOrderAppraise.getEfficiency().intValue()>=2 &&
                    workOrderAppraise.getResult().intValue()>=2)
                {
                    workOrderAppraise.setSatisfactionLevel(SatisfactionLevel._WOSL1);
                }
                else
                {
                    workOrderAppraise.setSatisfactionLevel(SatisfactionLevel._WOSL2);
                }
                workOrderAppraise.initCommonField();
                workOrderAppraiseWriteMapper.insertSelective(workOrderAppraise); 
            }
            else if (ScheduleStatus.EVALUATION.equals(workOrder.getScheduleStatus()))
            {
                throw LandseaException.createException(WorkOrderResultCode.E008500013);
            }
            else 
            {
                throw LandseaException.createException(WorkOrderResultCode.E008500014);
            } 
        }
        catch (LandseaException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            LOGGER.error("insertWorkOrderAppraise|评价工单失败.", e);
            throw LandseaException.createException(WorkOrderResultCode.E008500011);
        }
    }
    
    public WorkOrderAppraise getWorkOrderAppraise(Integer woId)throws LandseaException
    {
        try
        {
            WorkOrder workOrder = workOrderReadMapper.selectByPrimaryKey(woId);
            if (null == workOrder)
            {
                throw LandseaException.createException(WorkOrderResultCode.E00850005);
            }
            WorkOrderAppraise workOrderAppraise = workOrderAppraiseReadMapper.selectByWOId(woId);
            return workOrderAppraise;
        }
        catch (LandseaException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            LOGGER.error("insertWorkOrderAppraise|评价工单失败.", e);
            throw LandseaException.createException(WorkOrderResultCode.E008500011);
        }
    }
    
    public void deleteWorkOrder(Integer id)throws LandseaException
    {
        try
        {
            WorkOrder workOrder = workOrderReadMapper.selectByPrimaryKey(id);
            if (null == workOrder)
            {
                throw LandseaException.createException(WorkOrderResultCode.E00850005);
            }
            if (!WorkOrderStatus.TOBESENT.equals(workOrder.getWorkOrderStatus()))
            {
                throw LandseaException.createException(WorkOrderResultCode.E008500016);
            }
            workOrderWriteMapper.deleteByPrimaryKey(workOrder);
            
        }
        catch (LandseaException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            LOGGER.error("deleteWorkOrder|删除工单失败.", e);
            throw LandseaException.createException(WorkOrderResultCode.E008500015);
        }
        
    }
    
    public List<WorkOrderListResp> getWorkOrderList(QueryUtil queryUtil)throws LandseaException
    {
        
        try
        {           
            List<WorkOrderListResp> resultResps = new ArrayList<WorkOrderListResp>();
            queryUtil.getParams().put("adminId", SecurityUtils.getCurrentLogin().getUserId());
            List<UserRoleDTO> userRoleList = userReadMapper.getUserRolesWithCodeByUserId(SecurityUtils.getCurrentLogin().getUserId());
            if (CollectionUtils.isEmpty(userRoleList))
            {
                throw LandseaException.createException(WorkOrderResultCode.E008500019);
            }
            for (UserRoleDTO userRole : userRoleList)
            {
                String destRoleCode = userRole.getCode();
                // 检查总部运营负责人  检查区域经理
                if (RoleCode.ZBYYFZR.equals(destRoleCode) || RoleCode.QYYYJL.equals(destRoleCode))
                {
                    resultResps = workOrderReadMapper.selectWorkOrderList(queryUtil);
                }
                // 检查店长  检查管家
                else if(RoleCode.DZ.equals(destRoleCode) || RoleCode.GJ.equals(destRoleCode))
                {
                    resultResps = workOrderReadMapper.selectWorkOrderListByDZ(queryUtil);
                }  
            }
            for (WorkOrderListResp workOrderListResp : resultResps)
            {
                if (null == workOrderListResp.getRoomId())
                {
                    workOrderListResp.setIsStay(false);
                }
                else
                {
                    workOrderListResp.setIsStay(true);
                }
                String workOrderColor = getWorkOrderColor(workOrderListResp.getOrderCreatedTime(),
                    workOrderListResp.getWorkOrderStatusCode());
                workOrderListResp.setWorkOrderColor(workOrderColor);
            }
            return resultResps;
        }
        catch (LandseaException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            LOGGER.error("getWorkOrderList|查询工单列表失败.", e);
            throw LandseaException.createException(WorkOrderResultCode.E008500017);
        }
        
    }
    
    public String getWorkOrderColor(Date orderCreatedTime, String workOrderStatus)
    {
        String color = new String();
        Date nowDate = new Date();
        Long timeGap = DateUtil.getTimeOfTwoDate(orderCreatedTime,nowDate);
        Configuration configuration2 = configurationService.get("SYS_WO_SENTTOAREAM_HOUR");
        Configuration configuration1 = configurationService.get("SYS_WO_SENTTOM_HOUR");
        Configuration configuration3 = configurationService.get("SYS_WO_UNCOMPLETEAREAM_HOUR");
        Long sentToAreaMTime = Long.parseLong(configuration2.getValue())*60*60;
        Long sentToMTime =  Long.parseLong(configuration1.getValue())*60*60;
        Long unComoleteAreaMTime =  Long.parseLong(configuration3.getValue())*60*60;
        //提醒店长(1小时之后还未指派)
        if (timeGap.intValue()>=sentToMTime.intValue() && 
            timeGap.intValue()<sentToAreaMTime.intValue() && 
            WorkOrderStatus.TOBESENT.equals(workOrderStatus)) 
        {
            color = "Yellow";            
        }
        //提醒区域运营经理(2小时之后还未指派)
        else if ( timeGap.intValue()>=sentToAreaMTime.intValue() && 
            WorkOrderStatus.TOBESENT.equals(workOrderStatus)) 
        {
            color = "Red";
        }
        //提醒区域运营经理（48小时还未处理完工）
        else if ( timeGap.intValue()>=unComoleteAreaMTime.intValue() && 
            (!(WorkOrderStatus.FORCEDFINISH.equals(workOrderStatus)) &&
                !(WorkOrderStatus.NORMALFINISH.equals(workOrderStatus)))    )
        {
            color = "Red";
        }
        //正常处理
        else 
        {
            color = "Green";
        }
        
        return color;
    }
    
    public List<WorkOrderReportListResp> getWorkOrderReportList(QueryUtil queryUtil)throws LandseaException
    {
        try
        {
            List<WorkOrderReportListResp> resultResps = new ArrayList<WorkOrderReportListResp>();
            queryUtil.getParams().put("adminId", SecurityUtils.getCurrentLogin().getUserId());
            List<UserRoleDTO> userRoleList = userReadMapper.getUserRolesWithCodeByUserId(SecurityUtils.getCurrentLogin().getUserId());
            if (CollectionUtils.isEmpty(userRoleList))
            {
                throw LandseaException.createException(WorkOrderResultCode.E008500019);
            }
            for (UserRoleDTO userRole : userRoleList)
            {
                String destRoleCode = userRole.getCode();
                // 检查总部运营负责人  检查区域经理
                if (RoleCode.ZBYYFZR.equals(destRoleCode) || RoleCode.QYYYJL.equals(destRoleCode))
                {
                    resultResps = workOrderReadMapper.selectWorkOrderReportList(queryUtil);
                }
                // 检查店长  检查管家
                else if(RoleCode.DZ.equals(destRoleCode) || RoleCode.GJ.equals(destRoleCode))
                {
                    resultResps = workOrderReadMapper.selectWorkOrderReportListByDZ(queryUtil);
                }  
            }
            
            for (WorkOrderReportListResp workOrderReportListResp : resultResps)
            {
                if (null == workOrderReportListResp.getRoomId())
                {
                    workOrderReportListResp.setIsStay(false);
                }
                else
                {
                    workOrderReportListResp.setIsStay(true);
                }
                if (null == workOrderReportListResp.getPreviousId())
                {
                    workOrderReportListResp.setPreviousWOCode(null);
                }
                else
                {
                    WorkOrder workOrder = workOrderReadMapper.selectByPrimaryKey(workOrderReportListResp.getPreviousId());
                    workOrderReportListResp.setPreviousWOCode(workOrder.getWorkOrderCode());
                }
                //第一次处理保存时间
                WorkOrderSchedule scheduleHandleTime = workOrderScheduleReadMapper.selectHandleTime(workOrderReportListResp.getId());  
                if (null ==scheduleHandleTime)
                {
                    workOrderReportListResp.setOrderTime(null);
                    workOrderReportListResp.setProcessingTime(null);
                }
                else
                {
                    //接单时长（第一次处理时间-创建时间）
                    Long orderTimel = DateUtil.getTimeOfTwoDate(workOrderReportListResp.getOrderCreatedTime(),scheduleHandleTime.getHandleTime());
                    Long orderTimes = orderTimel%60;
                    Long orderTimem = orderTimel/60%60;
                    Long orderTimeh = orderTimel/60/60;
                    if (0== orderTimeh && 0==orderTimem )
                    {
                        workOrderReportListResp.setOrderTime(orderTimes+"秒");
                    }
                    else if (0 == orderTimeh && 0==orderTimes )
                    {
                        workOrderReportListResp.setOrderTime(orderTimem+"分钟");
                    }
                    else if (0==orderTimem && 0==orderTimes )
                    {
                        workOrderReportListResp.setOrderTime(orderTimeh+"小时");
                    }
                    else if (0== orderTimeh)
                    {
                        workOrderReportListResp.setOrderTime(orderTimem+"分钟"+orderTimes+"秒");
                    }
                    else if (0== orderTimem)
                    {
                        workOrderReportListResp.setOrderTime(orderTimeh+"小时"+orderTimes+"秒");
                    }
                    else if (0== orderTimes)
                    {
                        workOrderReportListResp.setOrderTime(orderTimeh+"小时"+orderTimem+"分钟");
                    }
                    else 
                    {
                        workOrderReportListResp.setOrderTime(orderTimeh+"小时"+orderTimem+"分钟"+orderTimes+"秒");
                    }
                    
                    //处理时长（完结时间-第一次处理保存时间）
                    if (null ==workOrderReportListResp.getCompletedTime())
                    {
                        workOrderReportListResp.setProcessingTime(null);
                    }
                    else
                    {                        
                        Long processingTimel = DateUtil.getTimeOfTwoDate(scheduleHandleTime.getHandleTime(),workOrderReportListResp.getCompletedTime());
                        Long processingTimes = processingTimel%60;
                        Long processingTimem = processingTimel/60%60;
                        Long processingTimeh = processingTimel/60/60;
                        if (0== processingTimeh && 0==processingTimem )
                        {
                            workOrderReportListResp.setProcessingTime(processingTimes+"秒");
                        }
                        else if (0 == processingTimeh && 0==processingTimes )
                        {
                            workOrderReportListResp.setProcessingTime(processingTimem+"分钟");
                        }
                        else if (0==processingTimem && 0==processingTimes )
                        {
                            workOrderReportListResp.setProcessingTime(processingTimeh+"小时");
                        }
                        else if (0== processingTimeh)
                        {
                            workOrderReportListResp.setProcessingTime(processingTimem+"分钟"+processingTimes+"秒");
                        }
                        else if (0== processingTimem)
                        {
                            workOrderReportListResp.setProcessingTime(processingTimeh+"小时"+processingTimes+"秒");
                        }
                        else if (0== processingTimes)
                        {
                            workOrderReportListResp.setProcessingTime(processingTimeh+"小时"+processingTimem+"分钟");
                        }
                        else 
                        {
                            workOrderReportListResp.setProcessingTime(processingTimeh+"小时"+processingTimem+"分钟"+processingTimes+"秒");
                        }
                    }
                }
            }
            return resultResps;
        }
        catch (Exception e)
        {
            LOGGER.error("getWorkOrderList|查询工单报表列表失败.", e);
            throw LandseaException.createException(WorkOrderResultCode.E008500018);
        }
        
    }
    
    public String downloadWorkOrderReport(QueryUtil queryUtil)throws LandseaException
    {
        StringBuffer url = propertyResolver.getProperty(REMOTE_PATH, StringBuffer.class, null);
        StringBuffer excelpath = propertyResolver.getProperty(EXCEL_PATH, StringBuffer.class, null);
        
        InputStream ins = null;
        Workbook wb = null;
        try
        {
            ins = WorkOrderService.class.getClassLoader().getResourceAsStream("工单报表.xlsx");
            wb = WorkbookFactory.create(ins);
        }
        catch (Exception e)
        {
            LOGGER.error("exportPropertyList error.", e);
        }
        finally
        {
            try
            {
                if (null != ins)
                {
                    ins.close();
                }
            }
            catch (IOException e)
            {
                LOGGER.error("exportPropertyList error.", e);
            }
        }
        
        List<WorkOrderReportListResp> list = getWorkOrderReportList(queryUtil);
        if (CollectionUtils.isEmpty(list))
        {
            throw LandseaException.createException(WorkOrderResultCode.E008500020);
        }
        //往excel里面存值
        if (list != null && list.size() > 0)
        {
            Sheet sheet = wb.getSheet("工单报表");
            // 生成一个样式
            CellStyle style = wb.createCellStyle();
            // 设置这些样式
            style.setAlignment(CellStyle.ALIGN_CENTER);
            // 生成一个字体
            Font font = wb.createFont();
            font.setFontHeightInPoints((short)14);
            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            // 把字体应用到当前的样式
            style.setFont(font);
            
            Row row;
            int startRow = 1;
            for (int i = 0; i < list.size(); i ++)
            {
                WorkOrderReportListResp object = list.get(i);
                
                row = sheet.createRow(startRow + i);
                //序号
                row.createCell(0).setCellValue(i + 1);
                //工单编号
                row.createCell(1).setCellValue(object.getWorkOrderCode() == null ? "" : object.getWorkOrderCode());
                //创建时间
                row.createCell(2).setCellValue(object.getOrderCreatedTime() == null ? "" : DateUtil.convertDateTime(object.getOrderCreatedTime()));
                //客户姓名
                row.createCell(3).setCellValue(object.getUserName() == null ? "" : object.getUserName());
                //手机号
                row.createCell(4).setCellValue(object.getUserPhone() == null ? "" : object.getUserPhone());
                //是否入住
                if (object.getIsStay() == false)
                {
                    row.createCell(5).setCellValue("否");
                }
                else if (object.getIsStay() == true)
                {
                    row.createCell(5).setCellValue("是");
                }
                else if (null == object.getIsStay())
                {
                    row.createCell(5).setCellValue("");
                }
               
                //城市公司
                row.createCell(6).setCellValue(object.getArea() == null ? "" : object.getArea());
                //项目
                row.createCell(7).setCellValue(object.getProjectName() == null ? "" : object.getProjectName());
                //房间号
                row.createCell(8).setCellValue(object.getRoomName() == null ? "" : object.getRoomName());
                //工单类型
                row.createCell(9).setCellValue(object.getOrderType() == null ? "" : object.getOrderType());
                //服务类型
                row.createCell(10).setCellValue(object.getServiceType() == null ? "" : object.getServiceType());
                //来源渠道
                row.createCell(11).setCellValue(object.getSourceChannel() == null ? "" : object.getSourceChannel());
                //原因/需求
                row.createCell(12).setCellValue(object.getDemand() == null ? "" : object.getDemand());
                //处理人
                row.createCell(13).setCellValue(object.getAssignedUserName() == null ? "" : object.getAssignedUserName());
                //接单时长
                row.createCell(14).setCellValue(object.getOrderTime() == null ? "" : object.getOrderTime());
                //处理过程
                row.createCell(15).setCellValue(object.getProcessingProgress() == null ? "" : object.getProcessingProgress());
                //处理时长
                row.createCell(16).setCellValue(object.getProcessingTime() == null ? "" : object.getProcessingTime());
                //完结时间
                row.createCell(17).setCellValue(object.getCompletedTime() == null ? "" : DateUtil.convertDateTime(object.getCompletedTime()));
                //事件总结
                row.createCell(18).setCellValue(object.getEndOfEvent() == null ? "" : object.getEndOfEvent());
                //工单状态
                row.createCell(19).setCellValue(object.getWorkOrderStatus() == null ? "" : object.getWorkOrderStatus());
                //是否重启
                if (object.getRestart() == false)
                {
                    row.createCell(20).setCellValue("否");
                }
                else if (object.getRestart() == true)
                {
                    row.createCell(20).setCellValue("是");
                }
                else if (null == object.getRestart())
                {
                    row.createCell(20).setCellValue("");
                }
                //历史工单编码
                row.createCell(21).setCellValue(object.getPreviousWOCode() == null ? "" : object.getPreviousWOCode());
                //责任部门
                row.createCell(22).setCellValue(object.getResponsibleDepartment() == null ? "" : object.getResponsibleDepartment());
                //满意度
                if (SatisfactionLevel._WOSL1.equals(object.getSatisfactionLevel()))
                {
                    row.createCell(23).setCellValue("满意");
                }
                else if(SatisfactionLevel._WOSL2.equals(object.getSatisfactionLevel()))
                {
                    row.createCell(23).setCellValue("不满意");
                }
                else if(null == object.getSatisfactionLevel())
                {
                    row.createCell(23).setCellValue("");
                }
                //客户备注
                row.createCell(24).setCellValue(object.getRemark() == null ? "" : object.getRemark());
               
               
            }
        }
        OutputStream fos = null;
        try
        {
            Integer userId = SecurityUtils.getCurrentLogin().getUserId();
            String filepath = fileConfiguration.getLocal() + "/" + excelpath;
            File file = new File(filepath);
            // 如果文件夹不存在则创建
            if (!file.exists() && !file.isDirectory())
            {
                file.mkdir();
            }
            // 删除userId开头的excel
            String[] files = file.list(new FilenameFilter()
            {
                @Override
                public boolean accept(File dir, String name)
                {
                    return name.endsWith(".xlsx");
                }
            });
            for (String f : files)
            {
                if (f.startsWith(userId + "-"))
                {
                    new File(filepath + "/" + f).delete();
                }
            }
            
            Date nowTime = new Date(System.currentTimeMillis());
            SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
            String time = sdFormatter.format(nowTime);
            
            String fileName = "工单报表_" + time +".xlsx";
            fos = new FileOutputStream(filepath + "/" + fileName);
            wb.write(fos);
            
            StringBuffer returnUrl = new StringBuffer();
            returnUrl.append(url);
            returnUrl.append("/");
            returnUrl.append(excelpath);
            returnUrl.append("/");
            returnUrl.append(fileName);
            return returnUrl.toString();
        }
        catch (Exception e)
        {
            LOGGER.error("exportPropertyList error.", e);
            return null;
        }
        finally
        {
            try
            {
                fos.flush();
                fos.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    
    @Override
    public void setEnvironment(Environment environment)
    {
        propertyResolver = new RelaxedPropertyResolver(environment, ENV_FILE_PATH);
        
    }
    
    public List<WorkOrderListResp> getWorkOrderListForWeChat() throws LandseaException
    {
        List<WorkOrderListResp> resultResps = new ArrayList<WorkOrderListResp>();
        try
        {
            Integer userId = SecurityUtils.getCurrentLogin().getUserId();
            resultResps = workOrderReadMapper.getWorkOrderListForWeChat(userId);
        }
        catch (Exception e)
        {
            LOGGER.error("getWorkOrderListForWeChat|查询微信端列表失败.", e);
            throw LandseaException.createException(WorkOrderResultCode.E008500017);
        }
        
        return resultResps;
    }
    
    /**
     * 
     * [简要描述]：</br>
     * [详细描述]：工单超过（配置的时间）还未指派，发送短信给店长</br>
     * [作者]：Crystal(2017-11-07)</br>
     *
     *
     */
    public void sendMessageToManager()
    {
        List<WorkOrderListResp> resps = workOrderReadMapper.selectWorkOrderListForMessage();
        if (CollectionUtils.isEmpty(resps))
        {
            return;
        }
        else
        {
            for (WorkOrderListResp workOrderListResp : resps)
            {
                Date nowDate = new Date();
                Long timeGap = DateUtil.getTimeOfTwoDate(workOrderListResp.getOrderCreatedTime(),nowDate);
                Configuration configuration = configurationService.get("SYS_WO_SENTTOM_HOUR");
                
                Long sentToMTime =  Long.parseLong(configuration.getValue())*60*60;
                //提醒店长(1小时之后还未指派)
                if (timeGap.intValue()>=sentToMTime.intValue() && 
                    timeGap.intValue()< (4*60*60) && 
                    WorkOrderStatus.TOBESENT.equals(workOrderListResp.getWorkOrderStatusCode())) 
                {
                    String msg = " {'store_name':'" + workOrderListResp.getProjectName()
                    + "','code_name':'" + workOrderListResp.getWorkOrderCode() + "'}";
                    List<AssignedUserResp> assignedUserResps =  workOrderReadMapper.getManagerByPrjId(workOrderListResp.getProjectId());
                    for (AssignedUserResp assignedUserResp : assignedUserResps)
                    {
                        String signName = configurationService.getStringValue(ConfigurationService.SEND_MSG_SIGN_NAME);
                        SMSUtil.sendSms(sendMsgConfiguration.getWorkOrderNotSentToManagerCode(), assignedUserResp.getUserPhone(), msg,signName);
                    } 
                }
            }  
        }
    }
    
    /**
     * 
     * [简要描述]：</br>
     * [详细描述]：工单超过（配置的时间）还未指派，发送短信给区域经理</br>
     * [作者]：Crystal(2017-11-07)</br>
     *
     *
     */
    public void sendMessageOfNotSent()
    {
        List<WorkOrderListResp> resps = workOrderReadMapper.selectWorkOrderListForMessage();
        if (CollectionUtils.isEmpty(resps))
        {
            return;
        }
        else
        {
            for (WorkOrderListResp workOrderListResp : resps)
            {
                Date nowDate = new Date();
                Long timeGap = DateUtil.getTimeOfTwoDate(workOrderListResp.getOrderCreatedTime(),nowDate);
                Configuration configuration = configurationService.get("SYS_WO_SENTTOAREAM_HOUR");
                Long sentToAreaMTime = Long.parseLong(configuration.getValue())*60*60;
                //提醒区域运营经理(2小时之后还未指派)
                if ( timeGap.intValue()>=sentToAreaMTime.intValue() && 
                    timeGap.intValue()< (4*60*60) && 
                    WorkOrderStatus.TOBESENT.equals(workOrderListResp.getWorkOrderStatusCode())) 
                {
                    String msg = " {'store':'" + workOrderListResp.getProjectName()
                    + "','code_name':'" + workOrderListResp.getWorkOrderCode() + "'}";
                    List<AssignedUserResp> assignedUserResps =  workOrderReadMapper.getAreaManagerByPrjId(workOrderListResp.getProjectId());
                    for (AssignedUserResp assignedUserResp : assignedUserResps)
                    {
                        String signName = configurationService.getStringValue(ConfigurationService.SEND_MSG_SIGN_NAME);
                        SMSUtil.sendSms(sendMsgConfiguration.getWorkOrderNotSentCode(), assignedUserResp.getUserPhone(), msg,signName);
                    } 
                }
            }
        }
    }
    
    /**
     * 
     * [简要描述]：</br>
     * [详细描述]：工单超过（配置的时间）还未处理完成，发送短信给区域经理</br>
     * [作者]：Crystal(2017-11-07)</br>
     *
     *
     */
    public void sendMessageOfNotHandle()
    {
        List<WorkOrderListResp> resps = workOrderReadMapper.selectWorkOrderListForMessage();
        if (CollectionUtils.isEmpty(resps))
        {
            return;
        }
        else
        {
            for (WorkOrderListResp workOrderListResp : resps)
            {
                Date nowDate = new Date();
                Long timeGap = DateUtil.getTimeOfTwoDate(workOrderListResp.getOrderCreatedTime(),nowDate);
                Integer dateGap = DateUtil.differentDaysByMillisecond(workOrderListResp.getOrderCreatedTime(),nowDate) - 1;
                Configuration configuration = configurationService.get("SYS_WO_UNCOMPLETEAREAM_HOUR");
                Long unComoleteAreaMTime =  Long.parseLong(configuration.getValue())*60*60;
                //提醒区域运营经理（48小时还未处理完工）
                if ( timeGap.intValue()>=unComoleteAreaMTime.intValue() && 
                    timeGap.intValue()< (4*60*60) && 
                    (!(WorkOrderStatus.FORCEDFINISH.equals(workOrderListResp.getWorkOrderStatusCode())) &&
                        !(WorkOrderStatus.NORMALFINISH.equals(workOrderListResp.getWorkOrderStatusCode())))    )
                {
                    String msg = " {'store':'" + workOrderListResp.getProjectName() 
                    + "','code_name':'" + workOrderListResp.getWorkOrderCode() 
                    + "','days':'" + dateGap + "'}";
                    List<AssignedUserResp> assignedUserResps =  workOrderReadMapper.getAreaManagerByPrjId(workOrderListResp.getProjectId());
                    for (AssignedUserResp assignedUserResp : assignedUserResps)
                    {
                        String signName = configurationService.getStringValue(ConfigurationService.SEND_MSG_SIGN_NAME);
                        SMSUtil.sendSms(sendMsgConfiguration.getWorkOrderNotHandleCode(), assignedUserResp.getUserPhone(), msg,signName);
                    } 
                    
                }
            }
            
        }
    }
    
    
    
}
